<template>
  <div style="display: flex; align-items: center;height: 100%">
    <div class="current-bundle" v-if="bundlesInfo || NPR">
      <el-popover
          width="280"
          placement="bottom"
          popper-class="requestTrial"
          trigger="hover">
        <div class="text" slot="reference" v-if="(bundlesInfo && bundlesInfo.name !== 'PROFESSIONAL') && !NPR">{{ bundlesInfo.name }}</div>
        <div>
          <div v-if="trialStatusData.status === 0">14-day trial ongoing. {{ trialStatusData.day }} days left. Ends on {{ GlobalTimeformat(trialStatusData.expirationTime, 'HH:mm:ss', $store.state.timeFormat)}}.</div>
          <div v-if="trialStatusData.status === 1">Your Professional Bundle trial has ended. Request to extend trial by 14 days?</div>
          <div v-if="trialStatusData.status === 2">Your request for an extension of 14 days for the Professional Bundle trial is currently being reviewed.</div>
          <div v-if="trialStatusData.status === 3">Discover the full potential of MSPbots Professional Bundle with our 14-day trial. Try it now!</div>
          <div class="btn-group">
            <el-button class="schedule" style="flex: 1" size="small" @click="jump" v-if="trialStatusData.status === 0 || trialStatusData.status === 1">Schedule a Demo</el-button>
            <el-button type="primary" style="flex: 1" size="small" @click="openRequestTrial" v-if="trialStatusData.status === 3 || trialStatusData.status === 1">Request</el-button>
          </div>
        </div>
      </el-popover>
      <div class="text" slot="reference" v-if="NPR || (bundlesInfo && bundlesInfo.name === 'PROFESSIONAL')">{{ NPR ? 'NFR' : bundlesInfo.name }}</div>
      <div class="btn" v-if="!NPR && (bundlesInfo && bundlesInfo.name !== 'PROFESSIONAL')" @click="alertOther">Upgrade Now</div>
    </div>
    <el-popover
        ref="request"
        popper-class="requestBundle"
        placement="bottom"
        width="280"
        v-model="$store.state.requestbtn.visible"
        trigger="manual">
      <div>
        <div>
          <div v-if="statusData.status === 0">You have {{ statusData.day }} days left in your Professional Bundle's 14-day trial. Your trial will expire on {{ GlobalTimeformat(statusData.expirationTime, 'HH:mm:ss', $store.state.timeFormat)}}.</div>
          <div v-if="statusData.status === 1">Your 14-day trial period for the Professional Bundle has ended.  Request to extend 14 days more.</div>
          <div v-if="statusData.status === 2">Your request to add another 14 days of Professional Bundle trial is under review. </div>
        </div>
        <div class="btn-group">
          <div class="btn request" @click="close();request(1)" v-if="statusData.status === 1">Request</div>
          <div class="btn request" @click="jump" v-if="statusData.status === 0">Schedule a Demo</div>
          <div class="btn" @click="close();$router.push({path: 'marketplace', query: {active: 'bundle'} })">Upgrade Now</div>
        </div>
      </div>
      <el-button @mouseenter.native="enter" class="request-btn" :class="{ 'request-btn-disable': statusData.status ===2 }" type="primary" size="mini" slot="reference" v-show="show && (statusData.status || statusData.status === 0)">{{ statusData.status === 0 ? `${statusData.day} Days Trial Left` : statusData.status === 1 ? 'PRO Bundle Trial Expired' : statusData.status === 2 ? 'Under Review' : '' }} </el-button>
    </el-popover>
    <z-notice :visible.sync="showNotice" v-bind="noticeObject" @ok="ok">
      <template v-slot:info v-if="!openNoticeStatus">
        {{$t('requestBundle.noticError')}} <span class="aLink" @click="showNotice=false; $router.push({path: 'marketplace', query: {active: 'bundle'} })">Marketplace</span>
      </template>
    </z-notice>
    <z-notice :visible.sync="showBundleAlert" v-bind="bundleAlertObject" @other="alertOther" @ok="alertOk" @close="closeNotice">
      <template v-slot:position v-if="nAbleCheckbox">
        <div class="remind"><el-checkbox v-model="nAbleChecked">Don't remind me again</el-checkbox></div>
      </template>
    </z-notice>
    <user-form-dialog ref="userFormDialog" width="450px" :userformDialogData="userFormDialogData" @envent="openNotice(true, 1)"></user-form-dialog>
    <user-form-dialog ref="requestTrial" width="450px" :userformDialogData="requestTrialData" @envent="openNotice(true, 2)"></user-form-dialog>
  </div>
</template>

<script>
import ZNotice from '@/components/storybook/z-dialog-notice'
import userFormDialog from '@/views/modules/mspbots/FormList/FormData/userFormDialog'
import config from '@/utils/config'
import { GlobalTimeformat } from '@/utils/common'
export default {
  name: 'request-bundle',
  components: {
    ZNotice,
    userFormDialog
  },
  data () {
    return {
      show: false,
      isOld: false,
      showNotice: false,
      showBundleAlert: false,
      openNoticeStatus: false,
      bundleAlertObject: {},
      noticeObject: {
        icon: '',
        info: '',
        okButton: {
          text: 'OK',
          type: 'primary'
        }
      },
      userFormDialogData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null
      },
      requestTrialData: {
        isNew: true,
        formTitle: null,
        formCode: null,
        id: null
      },
      statusData: {},
      approveStatus: false,
      GlobalTimeformat,
      user: null,
      nAbleChecked: false,
      nAbleCheckbox: false,
      bundlesInfo: null,
      bundlesPopoverText: '',
      bundlesButtonText: 'Request',
      bundlesButtonDisable: false,
      trialStatusData: {},
      NPR: false
    }
  },
  watch: {
    '$store.state.app.dayLeft' () {
      this.getRequestStatus()
    }
  },
  filter: {
    capitalizeFirstLetter(str) {
      return str.toLowerCase().replace(/(^|\s)\S/g, function (match) {
        return match.toUpperCase();
      });
    }
  },
  methods: {
    enter () {
      this.$store.commit('SET_VISBLE_STATUS', true)
    },
    openQuestion () {
      this.userFormDialogData = { isNew: true, formCode: config.requestToAdd14DaysMore, formTitle: 'Request to add 14 days more' }
      this.$refs.userFormDialog.visible = true
    },
    openRequestTrial () {
      this.requestTrialData = { isNew: true, formCode: config.request14DaysTrial, formTitle: 'Request 14 Days-trial' }
      this.$refs.requestTrial.visible = true
    },
    openNotice (bol, type) {
      this.openNoticeStatus = bol
      const emailLink = `mailto:support@mspbots.ai`
      this.noticeObject = {
        type,
        icon: bol ? 'icon_message_alt_check' : 'icon_message-alt-error',
        info: bol ? this.$t('requestBundle.noticSuccess') : this.$t('requestBundle.noticError2', { emailLink }),
        okButton: {
          text: 'OK',
          type: 'primary'
        }
      }
      this.showNotice = true
      if (bol) {
        this.requestDay(type)
      }
    },
    async request (type) {
      await this.approve(type)
      if (this.approveStatus) {
        this.openQuestion()
      } else {
        this.openNotice(false)
      }
    },
    getStatus (type) {
      this.$interface.pay.getExpirationTime({ type }).then(res => {
        if (res.data.code === 0) {
          if (type === 1) {
            this.statusData = res.data.data
          }
          if (type === 2) {
            this.trialStatusData = res.data.data
          }
        }
      })
    },
    async approve (type) {
      await this.$interface.pay.getAutoApprove({type}).then(res => {
        if (res.data.code === 0) {
          this.approveStatus = res.data.data
        }
      })
    },
    requestDay (type) {
      this.$interface.pay.requestDay({type}).then(res => {})
    },
    async getBundleInfo (res) {
      const data = res.data
      this.customer = data.data.customer || {}
      if (this.customer.id) {
        const { subList } = this.$interface.pay
        const { data } = await subList({ tenantCode: this.$store.state.user.tenantCode })
        this.bundlesInfo = this._.find(data.data, { type: 0 })
        if (this.bundlesInfo) {
          this.getStatus(2)
        }
        if (data.data.length > 0) {
          return false
        } else {
          return true
        }
      } else {
        return true
      }
    },
    async getOld (res) {
      if (res.data.code === 0) {
        this.nAbleCheckbox = res.data.data.isCheckbox
        this.isOld = res.data.data.isPopup
        this.NPR = res.data.data.NPR
        if (res.data.data.expire) {
          this.getStatus(1)
        }
      }
    },
    ok () {
      this.getStatus(this.noticeObject.type)
    },
    async getRequestStatus () {
      const { getCustomerAndCard, getOld } = this.$interface.pay
      const data = await getCustomerAndCard()
      this.show = await this.getBundleInfo(data)
      const data2 = await getOld({ type: this.bundlesInfo ? 2 : 1 })
      await this.getOld(data2)
      if (this.show && this.isOld && this.statusData.status === 1 && !sessionStorage.getItem('bundleAlert') && !this.bundlesInfo) {
        this.requestBundleAlert()
      }
    },
    close () {
      this.$refs.request.doClose()
    },
    jump () {
      this.$refs.request.doClose()
      window.open('https://wiki.mspbots.ai/x/MYJ6AQ')
    },
    requestBundleAlert () {
      this.bundleAlertObject = {
        icon: 'icon_message-alt-error',
        info: this.$t('requestBundle.requestBundleAlert'),
        otherButton: {
          text: 'Upgrade your subscription',
          type: 'primary'
        },
        okButton: {
          text: 'Request to extend 14 days Trial'
        },
        closeButton: {
          text: 'Close'
        }
      }
      this.showBundleAlert = true
      sessionStorage.setItem('bundleAlert', 'true')
    },
    alertOther () {
      this.$router.push({ path: '/marketplace', query: { active: 'bundle' } })
    },
    alertOk () {
      this.request(1)
    },
    closeNotice () {
      if ( this.nAbleChecked) {
        const params = {
          userId: this.$store.state.user.id,
          value: true,
          keyword: 'isCheckbox'
        }
        const  { postSettingUserApi } = this.$interface.system
        postSettingUserApi(params)
      }
    },
  },
  async created () {
    await this.getRequestStatus()
  }
}
</script>

<style lang="scss">
.aLink {
  color: #454171;
  text-decoration: none;
  cursor: pointer;
  &:hover {
    color: #17114d;
    text-decoration: underline;
  }
}
.request-btn {
  width: 200px;
  font-size: 14px !important;
  color: #FFF5E3 !important;
  background: #FFB32B !important;
  border-radius: 4px !important;
  border: none !important;
}
.request-btn-disable {
  background: #F9F9F94C !important;
}
.requestBundle[x-placement^=bottom]{
  background: #001141;
  border-radius: 2px;
  color: #FFFFFF;
  font-size: 14px;
  line-height: 20px;
  border: none;
  text-align: center;
  word-break: break-word;
  .btn-group{
    display: flex;
    margin-top: 12px;
    div{
      flex: 1;
      line-height: 30px;
      background: #0043CE;
      border-radius: 2px 2px 2px 2px;
      text-align: center;
      font-size: 14px;
      cursor: pointer;
    }
    div:nth-child(2) {
      margin-left: 9px;
    }
    .request{
      background: rgba(255,255,255,0.06);
    }
  }
  .popper__arrow::after{
    border-bottom-color: #001141 !important;
  }
}
.remind {
  position: absolute;
  left: 10px;
  bottom: 10px
}

.current-bundle {
  height: 30px;
  border-radius: 4px;
  border: 1px solid rgba(255,255,255,0.07);
  background: rgb(20, 46, 124);
  display: flex;
  align-items: center;
  padding: 0 4px 0 8px;
  margin-right: 50px;
  &:hover {
    background: rgb(47,71,139);
  }
  .text {
    padding: 0 14px 0 8px;
  }
  .btn {
    position: relative;
    background: #17b3a3;
    border-radius: 2px;
    height: 22px;
    line-height: 22px;
    padding: 0 8px;
    font-size: 12px;
    margin-left: 8px;
  }
  .btn::before{
    content: '';
    display: block;
    height: 10px;
    width: 1px;
    background: #FFFFFFBA;
    position: absolute;
    left: -7px;
    top: 50%;
    transform: translateY(-50%);
  }
}
.requestTrial {
  background: #001141 !important;
  border-radius: 2px !important;;
  color: #FFFFFF !important;;
  font-size: 14px !important;;
  line-height: 20px !important;;
  border: none !important;;
  text-align: center !important;;
  word-break: break-word !important;;
  .popper__arrow::after{
    border-bottom-color: #001141 !important;
  }
  .btn-group{
    display: flex;
    margin-top: 12px;
    .schedule {
      background: #113258FF;
      color: #FFFFFF;
      border-color: #113258FF;
    }
  }
}
</style>
